<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="utf-8">
    <meta name="viewport"
          content="width=device-width, initial-scale=1, maximum-scale=1.0, user-scalable=0,shrink-to-fit=no, viewport-fit=cover">
    <meta name="keywords" content="蓝桥到家">
    <meta name="description" itemprop="description" content="生鲜副食、饮品乳品、鲜花蛋糕">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>登录</title>
    <link rel="stylesheet" type="text/css" href="../styles/reset.css"/>
    <link rel="stylesheet" type="text/css" href="../styles/login.css">
    <link rel="stylesheet" type="text/css" href="../styles/common.css"/>
    <script src="../js/common.js"></script>
    <script src="../js/zepto.min.js"></script>
    <script src="https://unpkg.com/vue@3/dist/vue.global.js"></script>
    <script src="https://unpkg.com/axios/dist/axios.min.js"></script>
    <style>
        .error {
            color: #ff4d4f;
            font-size: 0.1rem;
            margin-top: 0.1rem;
            display: block;
        }
        .code {
            background-color: #1677ff;
        }
        .code.disabled {
            background-color: #ccc;
            cursor: not-allowed;
        }
    </style>
</head>

<body>
<div class="wrap" id="app">
    <div class="container">
        <!-- logo start-->
        <div class="header_logo">
            <img src="https://static.shiyanlou.com/lanqiao/frontend/dist/img/lanqiao-logo.1bbdf85.svg"/>
        </div>
        <!-- logo end -->

        <ul class="login_tab">
            <li :class="{cur: loginType === 'captcha'}" @click="loginType = 'captcha'">
                <span>验证码登录</span>
            </li>
            <li :class="{cur: loginType === 'password'}" @click="loginType = 'password'">
                <span>密码登录</span
                ></li>
        </ul>
        <!-- 登录 start-->
        <ul class="login_show">
            <li v-if="loginType === 'captcha'" class="cur">
                <div class="login_item">
                    <span class="login_text">手机号</span>
                    <input class="login_input"
                           type="tel" maxlength="11"
                           v-model="form.phone"
                           @blur="validateField('phone')"
                           placeholder="输入手机号"/>
                    <span class="error" v-if="errors.phone">{{errors.phone}}</span>
                </div>
                <div class="login_item">
                    <span class="login_text">验证码</span>
                    <div class="auth_div">
                        <input class="login_input"
                               type="text" maxlength="4"
                               v-model="form.captcha"
                               @blur="validateField('captcha')"
                               placeholder="输入验证码"/>
                        <span class="error" v-if="errors.captcha">{{errors.captcha}}</span>
                        <div class="code"  @click="getCaptcha" :class="{disabled:isCodeDisabled}">
                            <span v-if="!isCodeDisabled">获取验证码</span>
                            <span v-else>{{countdown}}秒后获取</span>
                        </div>
                    </div>
                </div>
                <div class="login_button">
                    <span @click="login">登录</span>
                </div>
            </li>
            <li v-if="loginType === 'password'" class="cur">
                <div class="login_item">
                    <span class="login_text">手机号</span>
                    <input class="login_input"
                           type="tel" maxlength="11"
                           v-model="form.phone"
                           @blur="validateField('phone')"
                           placeholder="输入手机号"/>
                    <span class="error" v-if="errors.phone">{{errors.phone}}</span>
                </div>
                <div class="login_item">
                    <span class="login_text">密码</span>
                    <input class="login_input"
                           type="password"
                           v-model="form.password"
                           @blur="validateField('password')"
                           maxlength="12"
                           placeholder="输入密码"/>
                    <span class="error" v-if="errors.password">{{errors.password}}</span>
                </div>
                <div class="login_button">
                    <span @click="login">登录</span>
                </div>
            </li>
        </ul>
        <!-- 登录 end-->
        <div class="register_div">
            <a class="register_text" href="register.html">注册账号</a></div>
    </div>
</div>
</div>
<script>
    const {createApp, ref, onMounted} = Vue
    createApp({
        setup() {
            onMounted(() => {
                loadRegisteredUsers(); // 页面加载时加载用户数据
            });
            const form = ref({
                phone: '',
                captcha: '',
                password: ''
            })
            const errors = ref({
                phone: '',
                captcha: '',
                password: ''
            })
            // 验证字段
            const validateField = (field) => {
                errors.value[field] = ''
                switch (field) {
                    case 'phone':
                        const phoneReg = /^1[3-9]\d{9}$/;
                        if (!form.value.phone) {
                            errors.value.phone = '请输入手机号码';
                        } else if (!phoneReg.test(form.value.phone)) {
                            errors.value.phone = '请输入有效的手机号码';
                        }
                        break;

                    case 'captcha':
                        if (!form.value.captcha) {
                            errors.value.captcha = '请输入验证码';
                        } else if (form.value.captcha.length !== 4) {
                            errors.value.captcha = '验证码错误';
                        }
                        break;

                    case 'password':
                        if (!form.value.password) {
                            errors.value.password = '请输入密码';
                        } else if (form.value.password.length < 6) {
                            errors.value.password = '密码长度不能少于6位';
                        } else if (form.value.password.length > 20) {
                            errors.value.password = '密码长度不能超过20位';
                        }
                        break;
                }

            }
            const loginType = ref('captcha')
            // 验证整个表单
            const validateForm = () => {
                let isValid = true;

                errors.value = {phone: '', captcha: '', password: ''};
                // 验证手机号
                validateField('phone');
                if (errors.value.phone) {
                    isValid = false;
                }
                // 根据登录类型验证相应字段
                if (loginType.value === 'captcha') {
                    validateField('captcha');
                    if (errors.value.captcha) {
                        isValid = false;
                    }
                } else {
                    validateField('password');
                    if (errors.value.password) {
                        isValid = false;
                    }
                }

                return isValid;


            }
            const isLoading = ref(false)
            const registeredUsers = ref([])

            const loadRegisteredUsers = async () => {
                try {
                    const response = await axios.get('http://localhost:3000/register');
                    console.log('接口返回数据:', response.data);
                    registeredUsers.value = response.data || [];
                    console.log('注册用户信息加载成功');
                } catch (error) {
                    console.error('加载注册用户信息失败:', error);
                    alert('系统初始化失败，请刷新页面重试');
                }
            };

            // 验证码相关状态
            const isCodeDisabled = ref(false) // 控制按钮是否禁用
            const countdown = ref(60) // 倒计时秒数
            let countdownTimer = null // 倒计时定时器

            //获取验证码
            const getCaptcha = async () => {
                //判断手机号是否有效
                validateField('phone')
                if (errors.value.phone) {
                    return;
                }

                //检查手机号是否已注册
                const isRegistered = registeredUsers.value.some(
                    user => user.phone === form.value.phone
                );
                if (!isRegistered) {
                    errors.value.phone = '该手机号未注册，请先注册';
                    return;
                }
                // 3. 模拟发送验证码
                try {

                    // 4. 启动倒计时
                    isCodeDisabled.value = true;
                    countdown.value = 60;

                    // 清除可能存在的旧定时器
                    if (countdownTimer) {
                        clearInterval(countdownTimer);
                    }

                    // 倒计时逻辑
                    countdownTimer = setInterval(() => {
                        countdown.value--;
                        if (countdown.value <= 0) {
                            clearInterval(countdownTimer);
                            isCodeDisabled.value = false;
                            countdown.value = 60;
                        }
                    }, 1000);

                    alert('验证码已发送，请注意查收');
                    console.log(`向手机号 ${form.value.phone} 发送验证码`);
                } catch (error) {
                    console.error('发送验证码失败:', error);
                    alert('获取验证码失败，请稍后重试');
                    isCodeDisabled.value = false; // 失败时恢复按钮可用
                }
            };


            //login
            const login = async () => {
                // 表单验证
                if (!validateForm()) {
                    return;
                }

                try {
                    isLoading.value = true;

                    // 查找注册用户
                    const user = registeredUsers.value.find(
                        u => u.phone === form.value.phone
                    );

                    // 验证用户是否存在
                    if (!user) {
                        console.log(registeredUsers.value);
                        alert('该手机号未注册，请先注册');
                        isLoading.value = false;
                        return;
                    }

                    // 根据登录类型验证
                    if (loginType.value === 'captcha') {
                        if (form.value.captcha !== '1234') {
                            errors.value.captcha = '验证码不正确';
                            isLoading.value = false;
                            return;
                        }
                    } else {
                        // 密码登录验证
                        if (form.value.password !== user.password) {
                            errors.value.password = '密码不正确';
                            isLoading.value = false;
                            return;
                        }
                    }

                    // 登录成功
                    alert('登录成功');
                    window.location.href = '../index.html';

                } catch (e) {
                    console.error('登录验证失败', e);
                    alert('登录失败，请稍后重试');
                } finally {
                    isLoading.value = false;
                }
            }

            return {
                form,
                errors,
                loginType,
                isCodeDisabled,
                countdown,
                getCaptcha,
                login,
                validateField,
                validateForm,
                loadRegisteredUsers

            }
        }
    }).mount('#app')
</script>
</body>

</html>